import { uploadImgUsingPost } from "@/services/novel-web/fileController";
import { getNovelInfoUsingGet, updateNovelUsingPost } from "@/services/novel-web/novelController";
import { listAllTagUsingGet } from "@/services/novel-web/tagController";
import { MessageError } from "@/utils/commonUtils";
import { isAnyBlank } from "@/utils/stringUtils";
import { UploadOutlined } from "@ant-design/icons";
import { Button, Divider, Form, Input, message, Row, Select, Tag, Upload } from "antd";
import TextArea from "antd/es/input/TextArea";
import { useEffect, useState } from "react";
import styles from "./NovelSettings.less";

interface ImgWrapperProps {
  value?: string;
  onChange?: (value:string) => void;
  className?: any;
  style?:any;
};

const ImgWrapper: React.FC<ImgWrapperProps> = ({value,onChange,className,style})=>{
  // const [val,setVal] = useState(value);
  return (
    <img
      className={className}
      style={style}
      src={value}
    />
  )
}


interface NovelSettingsProps {
  novelId: number;
}

const NovelSettings : React.FC<NovelSettingsProps> = ({novelId})=>{
  
  // init
  const [tagOptions,setTagOptions] = useState<API.TagVO[]>([]);
  const [info,setInfo] = useState<API.NovelInfo>({});

  const [form] = Form.useForm();
    
  

  const loadTagOptions = async ()=>{
    try {
      const resp = await listAllTagUsingGet();
      setTagOptions(resp.data ?? []);
      
    } catch (error) {
      MessageError(error);
    }
  };
  const loadNovelInfo = async()=>{
    try {
      const resp = await getNovelInfoUsingGet({
        id: novelId,
      });
      setInfo(resp.data ?? {});
    } catch (error) {
      MessageError(error);
    }
    
  };
  useEffect(()=>{
    // loadTagOptions();
    loadNovelInfo();
  },[]);


  useEffect(()=>{
    form.setFieldValue('cover',info.cover);
    form.setFieldValue('name',info.name);
    form.setFieldValue('description',info.description);
    form.setFieldValue('isEnd',info.isEnd);
  },[info])

  const cover_ = Form.useWatch('cover',form);
  const name_ = Form.useWatch('name',form);
  const description_ = Form.useWatch('description',form);
  const isEnd_ = Form.useWatch('isEnd',form);

  const [editable,setEditable] = useState(false);

  // start to alter button
  const handleStartToAlter = ()=>{
    setEditable(true);
  };

  // update button
  const [disClick,setDisClick] = useState(true);
  const handleValuesChange = ()=>{
    if(editable) {
      if(isAnyBlank(cover_,name_,description_)) {
        setDisClick(true);
      }
      else {
        setDisClick(false);
      }
    }
  };

  // upload cover
  const handleUpload = async (file)=>{
 
    try {
      const resp = await uploadImgUsingPost({
        file: file,
      })
      if(resp.data ) {
        const resp1 = await updateNovelUsingPost({
          id: novelId,
          cover: resp.data,
        })

        if(resp1.data) {
          setInfo({...info,
            cover: resp.data,
          })
          message.success('上传成功');
        }
       
      }
      
    } catch (error) {
      MessageError(error);
    }
    
  }

  // updata settings
  const handleUpdataSettings = async ()=> {
    // const ids = form_tags.map(tag => tag.id).join(',');
    try {
      const resp = await updateNovelUsingPost({
        id: novelId,
        // cover: cover_,
        name: name_,
        description: description_,
        isEnd: isEnd_,
      })
      if(resp.data) {
        message.success('修改成功');
        setInfo({...info,
          cover: cover_,
          name:name_,
          description:description_,
          isEnd: isEnd_,
        })
        setEditable(false);
      }
    } catch (error) {
      MessageError(error);
    }
  };

  // cancel button
  const handleCancel = ()=>{
    setEditable(false);
    // back reset
    form.setFieldValue('cover',info.cover);
    form.setFieldValue('name',info.name);
    form.setFieldValue('description',info.description);
    form.setFieldValue('isEnd',info.isEnd);
    
  }
  

  return (<>
    <Row align={"middle"} justify={"space-between"} style={{ margin: 8 }}>
      <div style={{ fontWeight: "bolder", fontSize: 16 }}>
        {"作品设置"}
      </div>
    </Row>
    <Divider />
    <Form
      form={form}
      onValuesChange={handleValuesChange}
    >
      <Form.Item label="作品封面" name="cover">
        <Form.Item name="cover">  
          <ImgWrapper className={styles.cover} value={cover_}/>
        </Form.Item>
        {/* TODO: upload cover */}
        <Upload
          customRequest={({file,onSuccess,onError})=>{
            handleUpload(file).then().catch(onError);
          }}
          showUploadList={false}
        >
          <Button>
            <span>上传自定义封面</span>
            <UploadOutlined />
          </Button>
        </Upload>
        
        
      </Form.Item>
      
      
      <Form.Item label="作品名称" name="name" >
        <Input 
          disabled={!editable}
        />
      </Form.Item>

      <Form.Item label="作品简介" name="description" >
        <TextArea 
          disabled={!editable} 
        />
        
      </Form.Item>

      <Form.Item label="连载状态" name="isEnd">
        <Select
          disabled={!editable}
        >
          <Select.Option value={0}>连载</Select.Option>
          <Select.Option value={1}>完结</Select.Option>
        </Select>
      </Form.Item>

      {/* <Form.Item label="标签" name="tags" > */}
      <Form.Item label="标签">
        
        {info.tags?.map((tag) => (
          <Tag>{tag.name}</Tag>
        ))}
      </Form.Item>
      
      {editable == false && (
        <Form.Item label={null} >
          <Button 
            type="primary"
            onClick={()=>handleStartToAlter()}
          >
            {"修改"}
          </Button>
        </Form.Item>
      )}

      {editable == true && (
        <Form.Item label={null}>
          <Button 
            disabled={disClick}
            type="primary" 
            onClick={()=>handleUpdataSettings()}
          >
            {"保存"}
          </Button>
          <Button 
            style={{marginLeft: '8px'}}
            type="primary" 
            onClick={()=>{handleCancel();}}
          >
            {"取消"}
          </Button>
        </Form.Item>
      )}
      
    </Form>
  </>);
}
 
export default NovelSettings;